package com.xiaoyu.izf.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.NumberUtil;
import com.xiaoyu.izf.model.UserInfo;
import com.xiaoyu.izf.multivalues.TwoValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class YqfStatsService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private TwoValue<Double,Integer> ordersAmountAndCount(UserInfo user, String startDate, String endDate){
        TwoValue<Double,Integer> tv = new TwoValue<>();

        String sql = "select ifnull(sum(t1.valid_order_amount),0) as ordersAmount," +
                " ifnull(sum(t1.valid_order_count),0) as ordersCount" +
                " from yqf_store_stats_day t1,yqf_store t2,yqf_merchant t3" +
                " where t1.store_id=t2.id and t2.merchant_id=t3.id and " +
                "t1.rec_date >=? and t1.rec_date<=? and t3.uid=?";

        Map<String,Object> map = jdbcTemplate.queryForMap(sql,startDate,endDate,user.getId());
        tv.setValue1(NumberUtil.div(Convert.toDouble(map.get("ordersAmount")).doubleValue(),100));
        tv.setValue2(Convert.toInt(map.get("ordersCount")));

        return tv;
    }

    /**
     * 订单总额
     * @param user
     * @param startDate
     * @param endDate
     * @return
     */
    public double ordersAmount(UserInfo user,String startDate,String endDate){
        return ordersAmountAndCount(user, startDate, endDate).getValue1();
    }

    /**
     * 订单数量
     * @param user
     * @param startDate
     * @param endDate
     * @return
     */
    public int ordersCount(UserInfo user,String startDate,String endDate){
        return ordersAmountAndCount(user, startDate, endDate).getValue2();
    }

    /**
     * 流水返佣金额
     * @param user
     * @param startDate
     * @param endDate
     * @return
     */
    public double serialCommission(UserInfo user,String startDate,String endDate){
        String sql = "select ifnull(sum(t4.commission),0) as commission" +
                " from yqf_commission_serial_log t4,yqf_store_stats_day t1,yqf_store t2,yqf_merchant t3" +
                " where t4.store_stats_day_id=t1.id and t1.store_id=t2.id and t2.merchant_id=t3.id and " +
                "t1.rec_date >=? and t1.rec_date<=? and t3.uid=?";

        Double commission = jdbcTemplate.queryForObject(sql,new Object[]{startDate,endDate,user.getId()},Double.class);
        if (commission==null)
            commission=0D;

        return commission;
    }
}
